package com.edu.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.service.addGoodsService;
import com.edu.service.impl.addGoodsServiceImpl;
import com.google.gson.Gson;

@WebServlet("/getGoodsById")
public class GoodsController extends HttpServlet {
    private addGoodsService goodsService = new addGoodsServiceImpl();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        try {
            int goodsId = Integer.parseInt(request.getParameter("goodsId"));
            Map<String, Object> goodsDetails = goodsService.getGoodsDetails(goodsId);
            
            if (goodsDetails != null) {
                response.getWriter().write(new Gson().toJson(goodsDetails));
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("{\"error\":\"商品不存在\"}");
            }
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("{\"error\":\"无效的商品ID\"}");
        }
    }
}